package com.zzw.springboot.controller;

import com.zzw.springboot.annotation.Log;
import com.zzw.springboot.bean.SysUser;
import com.zzw.springboot.mapper.SysUserMapper;
import com.zzw.springboot.security.JwtUtils;
import com.zzw.springboot.service.SysUserService;
import com.zzw.springboot.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录控制器
 * @author 赵志伟
 * @version 1.0
 */
@Api(tags = "登录管理")
@RestController
@RequestMapping("/login")
public class LoginController {

    @Resource
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 用户登录
     * @param loginForm 登录表单
     * @param request HTTP请求
     * @return 登录结果
     */
    @ApiOperation("用户登录")
    @PostMapping("/")
    @Log(module = "用户认证", type = "登录", description = "用户登录系统")
    public Result login(@RequestBody Map<String, String> loginForm, HttpServletRequest request) {
        try {
            // 获取用户名和密码
            String username = loginForm.get("username");
            String password = loginForm.get("password");

            // 参数校验
            if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
                return Result.error("用户名或密码不能为空");
            }

            // 使用Spring Security进行认证
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(username, password));

            // 设置认证信息
            SecurityContextHolder.getContext().setAuthentication(authentication);

            // 生成JWT令牌
            String token = jwtUtils.generateToken((UserDetails) authentication.getPrincipal());

            // 获取用户信息
            SysUser user = sysUserMapper.selectUserByUsername(username);

            // 更新登录信息
            user.setLastLoginTime(new Date());
            user.setLastLoginIp(request.getRemoteAddr());
            sysUserService.updateById(user);

            // 返回用户信息和JWT Token
            Map<String, Object> data = new HashMap<>();
            data.put("token", "Bearer " + token);  // 添加Bearer前缀
            data.put("userId", user.getId());
            data.put("username", user.getUsername());
            data.put("nickname", user.getNickname());
            data.put("avatar", user.getAvatar());

            return Result.success(data);
        } catch (DisabledException e) {
            return Result.error("账号已被禁用，请联系管理员");
        } catch (BadCredentialsException e) {
            return Result.error("用户名或密码错误");
        } catch (Exception e) {
            return Result.error("登录失败：" + e.getMessage());
        }
    }

    /**
     * 用户登出
     * @param request HTTP请求
     * @return 登出结果
     */
    @ApiOperation("用户登出")
    @PostMapping("/logout")
    @Log(module = "用户认证", type = "登出", description = "用户退出系统")
    public Result logout(HttpServletRequest request) {
        // 清除Spring Security上下文
        SecurityContextHolder.clearContext();
        return Result.success("退出成功");
    }

    /**
     * 获取当前用户信息
     * @return 当前用户信息
     */
    @ApiOperation("获取当前用户信息")
    @GetMapping("/getInfo")
    public Result getInfo() {
        try {
            // 获取当前认证的用户信息
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication != null && authentication.isAuthenticated()) {
                UserDetails userDetails = (UserDetails) authentication.getPrincipal();

                // 查询用户详细信息
                SysUser user = sysUserMapper.selectUserByUsername(userDetails.getUsername());

                if (user != null) {
                    Map<String, Object> data = new HashMap<>();
                    data.put("userId", user.getId());
                    data.put("username", user.getUsername());
                    data.put("nickname", user.getNickname());
                    data.put("avatar", user.getAvatar());
                    data.put("status", user.getStatus());
                    data.put("email", user.getEmail());
                    data.put("mobilePhone", user.getMobilePhone());

                    // 返回用户权限信息 - 从Authentication对象获取权限列表
                    data.put("permissions", authentication.getAuthorities());

                    return Result.success(data);
                } else {
                    return Result.error("未找到用户信息");
                }
            } else {
                return Result.error("用户未认证");
            }
        } catch (Exception e) {
            return Result.error("获取用户信息失败：" + e.getMessage());
        }
    }
}
